﻿using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.NLogSdk;
using ThresholdAssistant.WebAPI.Models;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.SemanticSemproxySearchResponse.Types;

namespace ThresholdAssistant.WebAPI.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class AliyunSmsService : BaseService, IBaseAutofac
    {
        // 参考文档：https://api.aliyun.com/api/Dysmsapi/2017-05-25/SendBatchSms?spm=a2c4g.11186623.0.0.ecd71295wxtum0&RegionId=cn-qingdao&tab=DEMO&lang=CSHARP
        // 博客园：https://www.cnblogs.com/stephenzengx/p/13679313.html

        //签名名称：武汉市青山区码动微技术开
        //签名值：武汉市青山区码动微技术开发有限公司
        //模版id：SMS_491165304
        //消息内容：尊敬的管理员${name}，提醒您：${event_name}在${date} ${ time}超出阈值${number}，请及时处理。

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="templateCode"></param>
        /// <param name="templateParam"></param>
        /// <returns></returns>
        public async Task<ContractResult<string>> SendSmsAsync(string phoneNumber="13548562645", string templateCode = "SMS_491165304", string templateParam = "")
        {
            var result = new ContractResult<string>();
            try
            {
                if (string.IsNullOrWhiteSpace(templateParam))
                {
                    templateParam = JsonConvert.SerializeObject(new
                    {
                        name = "张三",
                        event_name = "阈值预警",
                        date = DateTime.Now.ToString("yyyy-MM-dd"),
                        time = DateTime.Now.ToString("HH:mm:ss"),
                        number = 5
                    });
                    //"{\"name\":\"张三\",\"event_name\":\"阈值预警\",\"date\":\"2023-10-01\",\"time\":\"12:00:00\",\"number\":\"5\"}"; // 默认参数
                }
                Aliyun.Credentials.Client credential = new Aliyun.Credentials.Client();
                AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                {
                    Credential = credential,
                    AccessKeyId = "LTAI5tAxUsaYZhheGdmB37i2",
                    AccessKeySecret = "ylCnI7gRlITsQpHGO8lIKmfhsyyEUq",
                    Endpoint = "dysmsapi.aliyuncs.com"
                };
                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                var client = new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
                var request = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest
                {
                    PhoneNumbers = phoneNumber,
                    SignName = "武汉市青山区码动微技术开",
                    TemplateCode = templateCode,
                    TemplateParam = templateParam
                };
                var response = await client.SendSmsAsync(request);
                if (response.Body.Code == "OK")
                {
                    return result.SetSuceccful();
                }
                else
                {
                    NLogUtil.Error($"短信发送失败: {response.Body.Message}");
                    return result.SetError(ErrorResultEnum.RequestApiFail);
                }
            }
            catch (Exception ex)
            {
                NLogUtil.Error($"发送短信异常:{ex}");
                return result.SetError(ErrorResultEnum.RequestApiFail);
            }
        }
    }
}
